"""GCNet in pytorch, modified by resnet



[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun.

    Deep Residual Learning for Image Recognition
    https://arxiv.org/abs/1512.03385v1
"""

import torch
import torch.nn as nn
from torchsummary import summary

from inplace_abn import InPlaceABN, InPlaceABNSync

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

class ContextBlock2d(nn.Module):

    def __init__(self, in_channels, planes, pool='att', fusions=['channel_add'], ratio=8):
        super(ContextBlock2d, self).__init__()
        assert pool in ['avg', 'att']
        assert all([f in ['channel_add', 'channel_mul'] for f in fusions])
        assert len(fusions) > 0, 'at least one fusion should be used'
        self.in_channels = in_channels
        self.planes = planes
        self.pool = pool
        self.fusions = fusions
        if 'att' in pool:
            self.conv_mask = nn.Conv2d(in_channels, 1, kernel_size=1)#context Modeling
            self.softmax = nn.Softmax(dim=2)
        else:
            self.avg_pool = nn.AdaptiveAvgPool2d(1)
        if 'channel_add' in fusions:
            self.channel_add_conv = nn.Sequential(
                nn.Conv2d(self.in_channels, self.planes // ratio, kernel_size=1),
                nn.LayerNorm([self.planes // ratio, 1, 1]),
                nn.ReLU(inplace=True),
                nn.Conv2d(self.planes // ratio, self.in_channels, kernel_size=1)
            )
        else:
            self.channel_add_conv = None
        if 'channel_mul' in fusions:
            self.channel_mul_conv = nn.Sequential(
                nn.Conv2d(self.in_channels, self.planes // ratio, kernel_size=1),
                nn.LayerNorm([self.planes // ratio, 1, 1]),
                nn.ReLU(inplace=True),
                nn.Conv2d(self.planes // ratio, self.in_channels, kernel_size=1)
            )
        else:
            self.channel_mul_conv = None

    def spatial_pool(self, x):
        batch, channel, height, width = x.size()
        if self.pool == 'att':
            input_x = x
            # [N, C, H * W]
            input_x = input_x.view(batch, channel, height * width)
            # [N, 1, C, H * W]
            input_x = input_x.unsqueeze(1)
            # [N, 1, H, W]
            context_mask = self.conv_mask(x)
            # [N, 1, H * W]
            context_mask = context_mask.view(batch, 1, height * width)
            # [N, 1, H * W]
            context_mask = self.softmax(context_mask)#softmax操作
            # [N, 1, H * W, 1]
            context_mask = context_mask.unsqueeze(3)
            # [N, 1, C, 1]
            context = torch.matmul(input_x, context_mask)
            # [N, C, 1, 1]
            context = context.view(batch, channel, 1, 1)
        else:
            # [N, C, 1, 1]
            context = self.avg_pool(x)
        return context

    def forward(self, x):
        # [N, C, 1, 1]
        context = self.spatial_pool(x)

        if self.channel_mul_conv is not None:
            # [N, C, 1, 1]
            channel_mul_term = torch.sigmoid(self.channel_mul_conv(context))
            out = x * channel_mul_term
        else:
            out = x
        if self.channel_add_conv is not None:
            # [N, C, 1, 1]
            channel_add_term = self.channel_add_conv(context)
            out = out + channel_add_term
        return out


class BasicBlock(nn.Module):
    """Basic Block for resnet 18 and resnet 34

    """

    #BasicBlock and BottleNeck block
    #have different output size
    #we use class attribute expansion
    #to distinct
    expansion = 1

    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()

        #residual function
        self.residual_function = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(out_channels * BasicBlock.expansion)
        )

        #shortcut, just like downsample
        self.shortcut = nn.Sequential()

        #the shortcut output dimension is not the same with residual function
        #use 1*1 convolution to match the dimension
        if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channels * BasicBlock.expansion)
            )

    def forward(self, x):
        return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))

class MultiheadGCBlock(nn.Module):
    """Basic Block for resnet 18 and resnet 34, with attention

    """
    expansion = 1
    def __init__(self, in_channels, out_channels, stride=1, num_heads=4):
        super(MultiheadGCBlock, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3, bias=False)
        self.bn = nn.BatchNorm2d(out_channels)
        self.relu = nn.ReLU(inplace=True)

        self.gc = nn.Conv2d(out_channels, out_channels * MultiheadGCBlock.expansion, kernel_size=3, padding=1, bias=False)
        self.gc_bn = nn.BatchNorm2d(out_channels * MultiheadGCBlock.expansion)
        self.tanh = nn.Tanh()

        self.multihead = nn.MultiheadAttention(embed_dim=18432, num_heads=num_heads)
        self.fm = nn.Conv2d(out_channels, out_channels, kernel_size=9, stride=2, bias=False)
        # # residual function
        # self.residual_function = nn.Sequential(
        #     nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),
        #     nn.BatchNorm2d(out_channels),
        #     nn.ReLU(inplace=True),
        #     nn.MultiheadAttention(embed_dim=out_channels, num_heads=num_heads),
        #     nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),
        #     nn.BatchNorm2d(out_channels * BasicBlock.expansion)
        # )

        #shortcut, just like downsample
        # self.shortcut = nn.Sequential()

        # #the shortcut output dimension is not the same with residual function
        # #use 1*1 convolution to match the dimension
        # if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
        #     self.shortcut = nn.Sequential(
        #         nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),
        #         nn.BatchNorm2d(out_channels * BasicBlock.expansion)
        #     )

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        x = self.relu(x)
        print(x.shape)
        # [channels, batch_size, height, width]
        x = self.fm(x)
        # 使用多头注意力机制计算全局上下文
        print(x.shape)
        x = x.permute(1, 2, 3, 0)  # 将特征图变换为[batch_size, height, width, channels]
        batch_size, height, width, channels = x.size()

        #将特征图转换为序列
        x = x.reshape(batch_size*height*width, channels).transpose(0, 1)
        # x = x.view(batch_size*height*width, channels).transpose(0, 1)  # 转换为序列，即[sequence_length, batch_size*height*width, channels]
        print(x.shape)
        attn_output, attn_weights = self.multihead(x, x, x)  # 计算多头注意力机制输出和权重
        attn_output = attn_output.transpose(0, 1).reshape(channels, batch_size, height, width)  # 将序列转换为特征图形式
        attn_output = self.gc(attn_output)
        attn_output = self.gc_bn(attn_output)
        attn_output = self.tanh(attn_output) 
        out = x + x * attn_output  # 公式中的残差连接和门控机制
        out = out.transpose(0, 1).reshape(batch_size, channels, height, width)  # 将特征图转换为原来的形式
        return out

class BottleNeck(nn.Module):
    """Residual block for resnet over 50 layers

    """
    expansion = 4
    def __init__(self, in_channels, out_channels, stride=1):
        super().__init__()
        self.residual_function = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False),
            nn.BatchNorm2d(out_channels * BottleNeck.expansion),
        )

        self.shortcut = nn.Sequential()

        if stride != 1 or in_channels != out_channels * BottleNeck.expansion:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False),
                nn.BatchNorm2d(out_channels * BottleNeck.expansion)
            )

    def forward(self, x):
        return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))

class GCNet(nn.Module):

    def __init__(self, block, context_block, num_block, num_classes=100):
        super().__init__()

        self.in_channels = 64

        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True))
        #we use a different inputsize than the original paper
        #so conv2_x's stride is 1

        self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
        self.conv3_x = self._make_layer(block, 128, num_block[1], 2)
        self.conv4_x = self._make_layer_gc(block, context_block, 256, num_block[2], 2)
        self.conv5_x = self._make_layer(block, 512, num_block[3], 2)
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        
        self.fc = nn.Linear(512 * block.expansion, num_classes)

    def _make_layer(self, block, out_channels, num_blocks, stride):
        """make resnet layers(by layer i didnt mean this 'layer' was the
        same as a neuron netowork layer, ex. conv layer), one layer may
        contain more than one residual block

        Args:
            block: block type, basic block or bottle neck block
            out_channels: output depth channel number of this layer
            num_blocks: how many blocks per layer
            stride: the stride of the first block of this layer

        Return:
            return a resnet layer
        """

        # we have num_block blocks per layer, the first block
        # could be 1 or 2, other blocks would always be 1
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))
            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)

    # used by GC
    def _make_layer_gc(self, block, context_block, out_channels, num_blocks, stride=1):
        # downsample = None
        # if stride != 1 or self.in_channels != out_channels * block.expansion:
        #     downsample = nn.Sequential(
        #         nn.Conv2d(self.in_channels, out_channels * block.expansion,
        #                   kernel_size=1, stride=stride, bias=False),
        #         nn.BatchNorm2d(out_channels * block.expansion),
        #     )

        layers = []
        layers.append(block(self.in_channels, out_channels, stride))
        self.in_channels = out_channels * block.expansion
        for i in range(1, num_blocks-1):
            layers.append(block(self.in_channels, out_channels))
        layers.append(context_block(self.in_channels, self.in_channels))
        layers.append(block(self.in_channels, out_channels))

        return nn.Sequential(*layers)

    def forward(self, x):
        output = self.conv1(x)
        output = self.conv2_x(output)
        output = self.conv3_x(output)
        output = self.conv4_x(output)
        output = self.conv5_x(output)
        output = self.avg_pool(output)
        output = output.view(output.size(0), -1)
        output = self.fc(output)

        return output
    
class GCNetFull(nn.Module):

    def __init__(self, block, context_block, num_block, num_classes=100):
        super().__init__()

        self.in_channels = 64

        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True))
        #we use a different inputsize than the original paper
        #so conv2_x's stride is 1

        self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
        self.conv3_x = self._make_layer_gc(block, context_block, 128, num_block[1], 2)
        self.conv4_x = self._make_layer_gc(block, context_block, 256, num_block[2], 2)
        self.conv5_x = self._make_layer_gc(block, context_block, 512, num_block[3], 2)
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)
        # self.fc = nn.Linear(256 * block.expansion, num_classes)

    def _make_layer(self, block, out_channels, num_blocks, stride):
        """make resnet layers(by layer i didnt mean this 'layer' was the
        same as a neuron netowork layer, ex. conv layer), one layer may
        contain more than one residual block

        Args:
            block: block type, basic block or bottle neck block
            out_channels: output depth channel number of this layer
            num_blocks: how many blocks per layer
            stride: the stride of the first block of this layer

        Return:
            return a resnet layer
        """

        # we have num_block blocks per layer, the first block
        # could be 1 or 2, other blocks would always be 1
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))
            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)

    # used by GC
    def _make_layer_gc(self, block, context_block, out_channels, num_blocks, stride=1):
        # downsample = None
        # if stride != 1 or self.in_channels != out_channels * block.expansion:
        #     downsample = nn.Sequential(
        #         nn.Conv2d(self.in_channels, out_channels * block.expansion,
        #                   kernel_size=1, stride=stride, bias=False),
        #         nn.BatchNorm2d(out_channels * block.expansion),
        #     )

        layers = []
        layers.append(context_block(self.in_channels, self.in_channels))
        layers.append(block(self.in_channels, out_channels, stride))
        self.in_channels = out_channels * block.expansion
        layers.append(context_block(self.in_channels, self.in_channels))
        for i in range(1, num_blocks):
            layers.append(context_block(self.in_channels, self.in_channels))
            layers.append(block(self.in_channels, out_channels))

        return nn.Sequential(*layers)

    def forward(self, x):
        output = self.conv1(x)
        output = self.conv2_x(output)
        output = self.conv3_x(output)
        output = self.conv4_x(output)
        output = self.conv5_x(output)
        output = self.avg_pool(output)
        output = output.view(output.size(0), -1)
        output = self.fc(output)

        return output
    
class GCNetFullAttention(nn.Module):

    def __init__(self, block, context_block, num_block, num_classes=100):
        super().__init__()

        self.in_channels = 64

        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True))
        #we use a different inputsize than the original paper
        #so conv2_x's stride is 1

        self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
        self.conv3_x = self._make_layer_gc_att(block, context_block, 128, num_block[1], 2)
        self.conv4_x = self._make_layer_gc(block, context_block, 256, num_block[2], 2)
        self.conv5_x = self._make_layer_gc(block, context_block, 512, num_block[3], 2)
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * block.expansion, num_classes)
        # self.fc = nn.Linear(256 * block.expansion, num_classes)

    def _make_layer(self, block, out_channels, num_blocks, stride):
        """make resnet layers(by layer i didnt mean this 'layer' was the
        same as a neuron netowork layer, ex. conv layer), one layer may
        contain more than one residual block

        Args:
            block: block type, basic block or bottle neck block
            out_channels: output depth channel number of this layer
            num_blocks: how many blocks per layer
            stride: the stride of the first block of this layer

        Return:
            return a resnet layer
        """

        # we have num_block blocks per layer, the first block
        # could be 1 or 2, other blocks would always be 1
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_channels, out_channels, stride))
            self.in_channels = out_channels * block.expansion

        return nn.Sequential(*layers)

    # used by GC
    def _make_layer_gc(self, block, context_block, out_channels, num_blocks, stride=1):
        # downsample = None
        # if stride != 1 or self.in_channels != out_channels * block.expansion:
        #     downsample = nn.Sequential(
        #         nn.Conv2d(self.in_channels, out_channels * block.expansion,
        #                   kernel_size=1, stride=stride, bias=False),
        #         nn.BatchNorm2d(out_channels * block.expansion),
        #     )

        layers = []
        layers.append(block(self.in_channels, out_channels, stride))
        self.in_channels = out_channels * block.expansion
        for i in range(1, num_blocks-1):
            layers.append(block(self.in_channels, out_channels))
        layers.append(context_block(self.in_channels, self.in_channels))
        layers.append(block(self.in_channels, out_channels))

        return nn.Sequential(*layers)
    
        # used by GC_att
    def _make_layer_gc_att(self, block, context_block, out_channels, num_blocks, stride=1):
        # downsample = None
        # if stride != 1 or self.in_channels != out_channels * block.expansion:
        #     downsample = nn.Sequential(
        #         nn.Conv2d(self.in_channels, out_channels * block.expansion,
        #                   kernel_size=1, stride=stride, bias=False),
        #         nn.BatchNorm2d(out_channels * block.expansion),
        #     )
        block=MultiheadGCBlock
        layers = []
        layers.append(block(self.in_channels, out_channels, stride))
        self.in_channels = out_channels * block.expansion
        for i in range(1, num_blocks-1):
            layers.append(block(self.in_channels, out_channels))
        layers.append(context_block(self.in_channels, self.in_channels))
        layers.append(block(self.in_channels, out_channels))

        return nn.Sequential(*layers)

    def forward(self, x):
        output = self.conv1(x)
        output = self.conv2_x(output)
        output = self.conv3_x(output)
        output = self.conv4_x(output)
        output = self.conv5_x(output)
        output = self.avg_pool(output)
        output = output.view(output.size(0), -1)
        output = self.fc(output)

        return output

def gcnet9():
    """ return a GCNet 9 object
    """
    return "GCNet-9", GCNet(BasicBlock, ContextBlock2d, [1, 1, 1, 1])

def gcnet18():
    """ return a GCNet 18 object
    """
    return "GCNet-18", GCNet(BasicBlock, ContextBlock2d, [2, 2, 2, 2])

def gcnet34():
    """ return a GCNet 34 object
    """
    return "GCNet-34", GCNet(BasicBlock, ContextBlock2d, [3, 4, 6, 3])

def gcnet50():
    """ return a GCNet 50 object
    """
    return "GCNet-50", GCNet(BottleNeck, ContextBlock2d, [3, 4, 6, 3])

def gcnet_full9():
    """ return a GCNet 9 object
    """
    return "GCNet-full-9", GCNetFull(BasicBlock, ContextBlock2d, [1, 1, 1, 1])

def gcnet_full18():
    """ return a GCNet 18 object
    """
    return "GCNet-full-18", GCNetFull(BasicBlock, ContextBlock2d, [2, 2, 2, 2])

def gcnet_full34():
    """ return a GCNet 34 object
    """
    return "GCNet-full-34", GCNetFull(BasicBlock, ContextBlock2d, [3, 4, 6, 3])

def gcnet_full50():
    """ return a GCNet 50 object
    """
    return "GCNet-full-50", GCNetFull(BottleNeck, ContextBlock2d, [3, 4, 6, 3])

def gcnet_full_att18():
    """ return a GCNet-full-att 18 object
    """
    return "GCNet-full-att-18", GCNetFullAttention(BasicBlock, ContextBlock2d, [2, 2, 2, 2])


def gcnet_full_att9():
    """ return a GCNet-full-att 9 object
    """
    return "GCNet-full-att-9", GCNetFullAttention(BasicBlock, ContextBlock2d, [1, 1, 1, 1])


if __name__ == "__main__":
    gcnet = gcnet_full50()[1].to(device)
    summary(gcnet, input_size=(3, 32, 32))

